package com.store.orm.mysql.reflection;

import com.store.orm.mysql.MySQLUtil;
import com.store.orm.mysql.crud.Update;
import com.store.orm.mysql.crud.impl.MySQLUpdate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author 宫静雨
 * @version 1.0
 */
public class UpdateProxy implements InvocationHandler {

    private MySQLUtil UTIL;
    private static final Logger logger = LoggerFactory.getLogger(UpdateProxy.class);

    private MySQLUpdate mySQLUpdate;

    public UpdateProxy(MySQLUpdate mySQLUpdate) {
        this.mySQLUpdate = mySQLUpdate;
        this.UTIL = mySQLUpdate.getUTIL();
    }

    public Update proxy() {
        return (Update) Proxy.newProxyInstance(mySQLUpdate.getClass().getClassLoader(),
                new Class[]{Update.class}, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object invoke = method.invoke(mySQLUpdate, args);
        Connection connection = UTIL.getConnection();

        if (method.getName().equals("update")) {
            LinkedHashMap<String, List<Object>> map =
                    (LinkedHashMap<String, List<Object>>) invoke;
            map.forEach((k, v) -> {
                try {
                    PreparedStatement ps = connection.prepareStatement(k);
                    for (int i = 0; i < v.size(); i++) {
                        ps.setObject(i + 1, v.get(i));
                    }
                    int update = ps.executeUpdate();
                    if (UTIL.isLogged()) {
                        logger.info(">>> {}", k);
                        logger.info("<<< {}", v);
                        if (update >= 1) {
                            logger.info("修改数据: {}", true);
                        } else {
                            logger.info("修改数据: {}", false);
                        }
                    }
                } catch (SQLException e) {
                    logger.error("执行SQL出错: {}", e.getMessage());
                }
            });
        }
        return null;
    }
}
